import socket
import re
from proxy import Proxy
from database import Database

class Connections:
	def __init__(self):
		self.db = Database()
		self._ip_regexp = re.compile("^(?P<ip>((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d))(?P<port>:[0-65535])$")
		self._url_regexp = re.compile("^((https?|ftp):\/\/)?(?P<host>[^\/]+)(\/.*)?$")

	def exists(self, src, dst):
		src = self._get_ip(src)
		dst = self._get_ip(dst)
		if not src or not dst:
			return False

		sql = "SELECT connections.idc_proxy FROM connections " + \
			"INNER JOIN proxys ON proxys.idproxy=connections.idc_proxy " + \
			"WHERE connections.src_ip = INET_ATON('" + src + "') " + \
			"AND connections.dst_ip = INET_ATON('" + dst + "') " + \
			"AND proxys.active=1 " + \
			"ORDER BY last"
		res = self.db.execute(sql, "tuple")
		if res.__len__() > 0:
			return True
		else:
			return False

	def _get_ip(self, path):
		res = self._ip_regexp.match(path)
		if res:
			return res.group('ip')
		else:
			res = self._url_regexp.match(path)
			if res:
				try:
					return socket.gethostbyname(res.group('host'))
				except:
					pass

			return False

	def get_proxy(self, src, dst):
		src = self._get_ip(src)
		dst = self._get_ip(dst)
		sql = "SELECT idc_proxy FROM connections " + \
			"WHERE src_ip = INET_ATON('" + src + "') AND dst_ip = INET_ATON('" + dst + "') order by last"
		res = self.db.execute(sql, "tuple")
		if res:
			return Proxy(res[0][0])
	
	def set(self, src, dst, proxy):
		src = self._get_ip(src)
		dst = self._get_ip(dst)
		sql = "INSERT INTO connections (idc_proxy, src_ip, dst_ip) VALUES (" + \
			str(proxy.id) + ", INET_ATON('" + src + "'), INET_ATON('" + dst + "'))"
		res = self.db.execute(sql, "tuple")
		
